package com.byxy.shop.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import com.byxy.shop.entity.ShoppingCartItem;
import com.byxy.shop.entity.User;
import com.byxy.shop.service.MyShoppingCartService;
import com.byxy.ssm.shop.vo.MyShoppingCartItemVO;

/**
 * @author 廖善椅
 * @ClassName CartController
 * @Description 购物车控制类
 * @date 2020年5月28日
 */

@Controller
public class CartController {

	@Autowired
	private MyShoppingCartService myShoppingCartService;

	@GetMapping("shop-cart")
	public String shopCart(Model model, HttpSession session) {
		User u = (User) session.getAttribute("newBeeMallUser");
		if (u == null) {
			return "redirect:/login";
		}
		List<MyShoppingCartItemVO> myShoppingCartItems = myShoppingCartService.getMyShoppingCartItems(u.getUserId());// new ArrayList<>();
		Integer itemsTotal = myShoppingCartService.cartCount();
		Integer priceTotal = 0;
		// 判断数据不为空
		if (!CollectionUtils.isEmpty(myShoppingCartItems)) {
			// 购物项总数（stream().mapToInt().sum()）
			itemsTotal = myShoppingCartItems.stream().mapToInt(MyShoppingCartItemVO::getGoodsCount).sum();
			if (itemsTotal < 1) {
				return "error/error_5xx";
			}
			// 总价
			for (MyShoppingCartItemVO shoppingCartItems : myShoppingCartItems) {
				priceTotal += shoppingCartItems.getGoodsCount() * shoppingCartItems.getSellingPrice();
			}
			if (priceTotal < 1) {
				return "error/error_5xx";
			}
		}
		model.addAttribute("myShoppingCartItems", myShoppingCartItems);
		model.addAttribute("itemsTotal", itemsTotal);
		model.addAttribute("priceTotal", priceTotal);
		return "mall/cart";
	}

	/**
	 * @description:加入购物车
	 */
	@PostMapping("shop-cart")
	@ResponseBody
	public Map<String, String> saveShoppingCartItem(@RequestBody ShoppingCartItem shoppingCartItem,
			HttpSession session) {
		Map<String, String> result = new HashMap<>();
		User u = (User) session.getAttribute("newBeeMallUser");
		ShoppingCartItem sct = myShoppingCartService.getById(shoppingCartItem.getGoodsId(),
				shoppingCartItem.getCartItemId());
		if (sct == null) {
			int car = myShoppingCartService.save(shoppingCartItem.getGoodsId(), shoppingCartItem.getGoodsCount(),
					u.getUserId());
			if (car == 1) {
				result.put("resultCode", "200");
			} else {
				result.put("resultCode", "201");
				result.put("message", "添加失败，请稍后重试！！");
			}
		} else {
			if (sct.getIsDeleted() == 0) {
				sct.setGoodsCount(sct.getGoodsCount() + shoppingCartItem.getGoodsCount());
			} else {
				sct.setGoodsCount(shoppingCartItem.getGoodsCount());
			}
			sct.setIsDeleted(0);
			int car = myShoppingCartService.updateCart(sct);
			if (car == 1) {
				result.put("resultCode", "200");
			} else {
				result.put("resultCode", "201");
				result.put("message", "添加失败，请稍后重试！！");
			}
		}

		return result;
	}

	/**
	 * @description 购物车数量修改
	 */
	@PutMapping("shop-cart")
	@ResponseBody
	public Map<String, String> updateShoppingCartItem(@RequestBody ShoppingCartItem shoppingCartItem,
			HttpSession session) {
		Map<String, String> result = new HashMap<>();
		User u = (User) session.getAttribute("newBeeMallUser");
		shoppingCartItem.setUserId(u.getUserId());
		shoppingCartItem.setCartItemId(shoppingCartItem.getCartItemId());
		shoppingCartItem.setGoodsCount(shoppingCartItem.getGoodsCount());
		shoppingCartItem.setIsDeleted(0);
		shoppingCartItem.setUpdateTime(new Date());
		int updateResult = myShoppingCartService.updateCart(shoppingCartItem);
		// 修改成功
		if (updateResult == 1) {
			result.put("resultCode", "200");
		} else {
			result.put("resultCode", "201");
			result.put("message", "添加失败，请稍后重试！！");
		}
		return result;
	}

	/**
	 * @description 删除购物车商品
	 */
	@DeleteMapping("shop-cart/{id}")
	@ResponseBody
	public Map<String, String> deleteShoppingCartItem(@PathVariable("id") Integer id, HttpSession session) {
		Map<String, String> result = new HashMap<>();
		int deleteResult = myShoppingCartService.deleteById(id);
		// 删除成功
		if (deleteResult == 1) {
			result.put("resultCode", "200");
		} else {
			result.put("resultCode", "201");
			result.put("message", "添加失败，请稍后重试！！");
		}
		return result;
	}

	/**
	 * @description 跳转结算页
	 */
	@GetMapping("shop-cart/settle")
	public String settlePage(Model model, HttpSession session) {
		Integer priceTotal = 0;
		User u = (User) session.getAttribute("newBeeMallUser");
		List<MyShoppingCartItemVO> myShoppingCartItems = myShoppingCartService.getMyShoppingCartItems(u.getUserId());
		if (CollectionUtils.isEmpty(myShoppingCartItems)) {
			// 无数据则不跳转至结算页
			return "/shop-cart";
		} else {
			// 总价
			for (MyShoppingCartItemVO shoppingCartItems : myShoppingCartItems) {
				priceTotal += shoppingCartItems.getGoodsCount() * shoppingCartItems.getSellingPrice();
			}
			if (priceTotal < 1) {
				return "error/error_5xx";
			}
		}
		model.addAttribute("myShoppingCartItems", myShoppingCartItems);
		model.addAttribute("priceTotal", priceTotal);
		return "mall/order-settle";
	}

}
